package com.atguigu.gulimall.member.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.gulimall.member.dao.MemberLevelDao;
import com.atguigu.gulimall.member.entity.MemberLevelEntity;
import com.atguigu.gulimall.member.entity.vo.MemberLoginVo;
import com.atguigu.gulimall.member.entity.vo.MemberRegistVo;
import com.atguigu.gulimall.member.entity.vo.SocialUser;
import com.atguigu.gulimall.member.exception.PhoneExistException;
import com.atguigu.gulimall.member.exception.UsernameExistException;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.member.dao.MemberDao;
import com.atguigu.gulimall.member.entity.MemberEntity;
import com.atguigu.gulimall.member.service.MemberService;


@Service("memberService")
public class MemberServiceImpl extends ServiceImpl<MemberDao, MemberEntity> implements MemberService {

    @Autowired
    MemberLevelDao memberLevelDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<MemberEntity> page = this.page(
                new Query<MemberEntity>().getPage(params),
                new QueryWrapper<MemberEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void regist(MemberRegistVo vo) {
        MemberEntity entity = new MemberEntity();

        //保存用户名和手机号前要检查唯一性
        checkPhoneUnique(vo.getPhone());
        checkUsernameUnique(vo.getUserName());

        entity.setUsername(vo.getUserName());
        entity.setMobile(vo.getPhone());

        //设置密码，需要加密，md5+盐值 encode加密 matches匹配
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encode = encoder.encode(vo.getPassword());

        entity.setPassword(encode);

        //获取默认等级
        MemberLevelEntity levelEntity = memberLevelDao.getDefaultLeve();
        entity.setLevelId(levelEntity.getId());
        entity.setCreateTime(new Date());

        entity.setNickname(vo.getUserName());

        this.baseMapper.insert(entity);
    }

    @Override
    public void checkPhoneUnique(String phone) throws PhoneExistException{

        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("mobile", phone));
        if (count > 0){
            throw  new PhoneExistException();
        }
    }

    @Override
    public void checkUsernameUnique(String userName) throws UsernameExistException {
        Integer count = this.baseMapper.selectCount(new QueryWrapper<MemberEntity>().eq("username", userName));
        if (count > 0){
            throw new UsernameExistException();
        }
    }

    @Override
    public MemberEntity login(MemberLoginVo loginVo) {

        String loginacct = loginVo.getLoginacct();
        String password = loginVo.getPassword();

        //去数据库查询
        //select * from ums_member where username=? OR mobile=?
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("username", loginacct).or().eq("mobile", loginacct));
        if (entity == null){
            //登录失败
            return null;
        }

        //比较数据库密码
        String dbPassword = entity.getPassword();
        boolean matches = new BCryptPasswordEncoder().matches(password, dbPassword);

        //匹配成功
        if (matches){
            return entity;
        }

        return null;

    }

    @Override
    public MemberEntity login(SocialUser socialUser) throws Exception {
        String uid = socialUser.getUid();
        MemberEntity entity = this.baseMapper.selectOne(new QueryWrapper<MemberEntity>().eq("social_uid", uid));
        if (entity != null){//用户以及注册,跟新token数据
            MemberEntity update = new MemberEntity();
            update.setId(entity.getId());
            update.setAccessToken(socialUser.getAccess_token());
            update.setExpiresIn(socialUser.getExpires_in());

            this.baseMapper.updateById(update);

            entity.setAccessToken(socialUser.getAccess_token());
            entity.setExpiresIn(socialUser.getExpires_in());
            return entity;
        }else {//是新用户
            MemberEntity regist = new MemberEntity();
            //查出社交用户信息https://api.weibo.com/2/users/show.json
            Map querys = new HashMap<String,String>();
            querys.put("access_token",socialUser.getAccess_token());
            querys.put("uid",socialUser.getUid());

            //查询信息失败不影响保存流程
            try {
                HttpResponse response = HttpUtils.doGet("https://api.weibo.com", "/2/users/show.json", "get", new HashMap<String, String>(), querys);
                if (response.getStatusLine().getStatusCode() == 200){
                    String s = EntityUtils.toString(response.getEntity());
                    JSONObject jsonObject = JSONObject.parseObject(s);
                    //昵称
                    String name = jsonObject.getString("name");
                    //性别
                    String gender = jsonObject.getString("gender");
                    //......
                    regist.setNickname(name);
                    regist.setUsername(name);
                    regist.setGender("m".equals(gender)?1:0);
                    //.......
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            regist.setSocialUid(socialUser.getUid());
            regist.setExpiresIn(socialUser.getExpires_in());
            regist.setAccessToken(socialUser.getAccess_token());

            //获取默认等级
            MemberLevelEntity levelEntity = memberLevelDao.getDefaultLeve();
            regist.setLevelId(levelEntity.getId());
            regist.setCreateTime(new Date());

            //.......

            this.baseMapper.insert(regist);

            return regist;
        }
    }

}